/**
 * Created with JetBrains WebStorm.
 * User: rekey
 * Date: 8/9/13
 * Time: 4:19
 * To change this template use File | Settings | File Templates.
 */
var async = require('async');
var dao = require('../dao/index.js');
var page = require('../lib/page.js');

exports.index = function defaultAction(req, res) {
  var slug = 'index';
  var currentPage = req.param('page') || 1;
  var locals = {
    currentCategory: slug,
    pageBaseUrl: '/page/'
  };

  if (res.locals.user) {
    console.log('locals.user is defined.');
  } else {
    console.log('locals.user is not defined.');
  }

  function getCategories(done) {
    dao.category.getList().then(function (categories) {
      done(null, categories);
    });
  }

  function getPostPages(done) {
    dao.post.getCount().then(function (count) {
      done(null, page.create(currentPage, count, 7));
    });
  }

  function getPosts(done) {
    dao.post.getList(currentPage).then(function (posts) {
      locals.posts = posts;
      done(null, posts);
    });
  }


  async.parallel({
    categories: getCategories,
    page: getPostPages,
    posts: getPosts
  }, function (err, results) {
    Object.keys(results).forEach(function (key) {
      locals[key] = results[key];
    });
    res.locals.data = locals;
    console.time('render:pages/category');
    res.render('pages/category');
    console.timeEnd('render:pages/category');
  });

};